package com.mall.manager.powerpart.service;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.util.WebUtils;

import com.mall.manager.user.service.ManageUserService;
import com.mall.untils.Page;

/**
 * 
 * @author LISIQIANG
 * 处理角色权限增、删、改、查业务层
 */

@Service("powerPartService")
public class ManagerPowerPartService {
	
	 private Logger logger = LoggerFactory.getLogger(ManageUserService.class);
	 @Resource
	 private JdbcTemplate jdbcTemplate;
	  		
		
		/**
		 * 角色权限修改
		 * @param paraMap
		 * @return
		 */
		@Transactional
		public void manager_power_part_edit(Map<String, Object> paraMap) {
			 String partIdRes=MapUtils.getString(paraMap, "partIdRes");
			 if(partIdRes!= null && !partIdRes.equals("0")){
			 String powerIds=MapUtils.getString(paraMap, "powerIds");
			 
			 String[]  arrayPowerIds = powerIds.split(",");
			 
			 String sqlDel="delete from t_power_part where part_id= ?";	
			 String sql="insert into t_power_part(part_id,power_id,create_time) values(?,?,now())";			 
			try {
				int updateDel = jdbcTemplate.update(sqlDel,partIdRes);
				if(updateDel==0){
					logger.info("角色权限删除失败！");
				}				
				
				for(int j=0;j<arrayPowerIds.length;j++){
					if(!arrayPowerIds[j].equals("on")){
					int update = this.jdbcTemplate.update(sql,partIdRes,arrayPowerIds[j]);
					if(update==0){
						logger.info("角色权限插入失败！");
					}
					}
				}
					
			} catch (Exception e) {  
				logger.info("角色权限修改失败！");
				
			}
			 }
			
		}
		
					 
		 /**
			 * 查询角色的对应权限
			 * @param request
			 * @return
			 */
			public List<Map<String, Object>> manager_power_part_listback(HttpServletRequest request) {
			
			    Map<String, Object> paraMap = WebUtils.getParametersStartingWith(request, "");			    
			    int part_id = MapUtils.getIntValue(paraMap, "partId");
			   
		    	try { 	 	       
		 	        
		 	        String sql = "select * from t_power_part where 1=1 ";
		 	        	              		 	      		 	        
		 	        if(part_id != 0){
			 	    	  sql += " and part_id = " + part_id ;
			 	    }		 	       		 	        
		 	        	        
		 	        List<Map<String, Object>> queryForList = this.jdbcTemplate.queryForList(sql);
		 	        
		 	        return queryForList;
		 	    } catch (Exception e) {
		 	        this.logger.info("角色权限列表失败");
		 	        return null;
		 	    }
			}
			
			
			/**
			 * 查询角色权限
			 * @param request
			 * @return
			 */
			public List<Map<String, Object>> manager_power_listback(HttpServletRequest request) {			
			   			   
		    	try { 	 	     		 	        
		 	        String sql = "select * from t_power ";		 	               
		 	        List<Map<String, Object>> queryForList = this.jdbcTemplate.queryForList(sql);
		 	        
		 	        return queryForList;
		 	    } catch (Exception e) {
		 	        this.logger.info("角色权限列表失败");
		 	        return null;
		 	    }
			}
			
			/**
			 * 找出需要回显得power
			 * @param request
			 * @return
			 */
			public void change_power_part_checked(HttpServletRequest request){
				
				String sql="update t_power set checked= 0";
				try {
					int update = jdbcTemplate.update(sql);
					if(update==0){
						logger.info("修改权限为非选择失败！");
					}
					
					List<Map<String, Object>>	powerList = manager_power_listback(request);
					
					List<Map<String, Object>> partPowerList = manager_power_part_listback(request);
					
					for(Map<String, Object> mappower:powerList){
						for(Map<String, Object> mappartpower:partPowerList){
							
							String idpower = String.valueOf(mappower.get("id"));
							String idpartpower = String.valueOf(mappartpower.get("power_id"));
														
							if(idpower.equals(idpartpower)){
								String sqlCheck="update t_power set checked= 1 where id=?";
								int updateCheck = jdbcTemplate.update(sqlCheck,idpower);
								if(updateCheck==0){
									logger.info("修改权限为选择失败！");
								}								
								break;
							}						
							
						}								
						}												
					
				} catch (Exception e) {
					logger.info("注册角色信息有问题！");
				
				}				
				
			}
			
			/**
			 * 
			 * @param request
			 * @param response
			 * @return
			 * @throws ServletException
			 * @throws IOException
			 */

			public List<Map<String, Object>> manager_power_part_assign(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap)throws ServletException, IOException {
				
			    Map<String, Object> paraMap = WebUtils.getParametersStartingWith(request, "");
			   	String partIdc =String.valueOf(MapUtils.getIntValue(paraMap, "partId")) ;
			   	modelMap.addAttribute("partIdc", partIdc);
			   				   
			    			    
		    	try { 		 	             		 	               
		 	       	String sql = "select * from t_part " ;		 	        		 	        	        
		 	        List<Map<String, Object>> queryForList = this.jdbcTemplate.queryForList(sql);		 	       
		 	        return queryForList;		 	        
		 	    } catch (Exception e) {
		 	        this.logger.info("获取角色列表失败");
		 	        return null;
		 	    }
			}			
			
			/**
			 * 
			 * @param request
			 * @param response
			 * @return
			 * @throws ServletException
			 * @throws IOException
			 */    
			
			public List<Map<String, Object>> manager_power_part_list(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
			    Map<String, Object> paraMap = WebUtils.getParametersStartingWith(request, "");	
			    String partName = MapUtils.getString(paraMap, "partName");
			    String sql = "select * from t_part " ;		
			    if(null!=partName&&!partName.equals("")){
			    	sql += " and remarks="+partName;
			    }
			    try{
		 	    List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql);
		 	    return queryForList;
		 	    } catch (Exception e) {
		 	        this.logger.info("获取角色列表失败");
		 	        return null;
		 	    }
			}
		
		
	 
	 /**
		 * 分页查询角色权限
		 * @param request
		 * @return
		 */
		@SuppressWarnings("deprecation")
		public Page manager_power_part_list(HttpServletRequest request) {
			Page page = null; 
		    Map<String, Object> paraMap = WebUtils.getParametersStartingWith(request, "");
		    int pageNo = MapUtils.getIntValue(paraMap, "pageNo");
		    int power_id = MapUtils.getIntValue(paraMap, "power_id");
		    int part_id = MapUtils.getIntValue(paraMap, "part_id");
		    int pageSize = 10;
	    	try { 
	 	        if (pageNo == 0){
	 	        	pageNo = 1;
	 	        }
	 	        
	 	        String sql = "select count(*) from t_power_part where 1=1 ";
	 	       
	 	       	if(power_id != 0){
	 	       		
	 	    	  sql += " and power_id = " + power_id ;
	 	        }
	 	       
	 	       if(part_id != 0){
	 	    	  sql += " and part_id = " + part_id ;
	 	        }
	 	       	 	         	       
	 	        int total = this.jdbcTemplate.queryForInt(sql);
	 	        int startIndex = Page.getStartOfPage(pageNo, pageSize); 	        
	 	        sql = "select * from t_power_part where 1=1 " ;	 	        
	 	        if(power_id != 0){
	  	    	  sql += " and power_id= " + power_id ;
	  	        }  	
	 	        
	 	        if(part_id != 0){
		 	    	  sql += " and part_id = " + part_id ;
		 	    }
	 	        
	 	        sql +=" order by id desc limit " + startIndex + "," + pageSize;
	 	        	        
	 	        List<Map<String, Object>> queryForList = this.jdbcTemplate.queryForList(sql);
	 	        page = new Page(startIndex, total, pageSize, queryForList);
	 	        return page;
	 	    } catch (Exception e) {
	 	        this.logger.info("角色权限列表失败");
	 	        return null;
	 	    }
		}
	 
		/**
		 * 
		 * @param request
		 * @param response
		 * @return根据角色Id获取权限
		 * @throws ServletException
		 * @throws IOException
		 */    
		
		public List<Map<String, Object>> getPowerbypartId(HttpServletRequest request,int level)throws ServletException, IOException {
		    Map<String, Object> paraMap = WebUtils.getParametersStartingWith(request, "");	
		    int partId =MapUtils.getIntValue(paraMap, "partId");
		    String  sql="";
		    try{
		    	if(partId==0){
		    		return null;
		    	}else{
		    		sql ="select * from t_power t join t_power_part pp on t.id=pp.power_id where pp.part_id="+partId+" and t.level="+level;
		    		List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql);
		    		return queryForList;
		    	}
	 	    } catch (Exception e) {
	 	        this.logger.info("获取权限列表失败");
	 	        return null;
	 	    }
		}
		
		
		/**
		 * 
		 * @param request
		 * @param response
		 * @return获取level权限
		 * @throws ServletException
		 * @throws IOException
		 */    
		
		public List<Map<String, Object>> getPowerbypartId(int level)throws ServletException, IOException {
		    String  sql="";
		    try{
		    	sql ="select * from t_power where level= "+level;
		    	List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql);
		    	return queryForList;
	 	    } catch (Exception e) {
	 	        this.logger.info("获取某level权限列表失败");
	 	        return null;
	 	    }
		}
		
		/**更新角色权限
		 * @param paraMap
		 * @return
		 */
		@Transactional
		public int manager_power_update(Map<String, Object> paraMap) {
			int part_id = MapUtils.getIntValue(paraMap, "part_id");
			String power_id = MapUtils.getString(paraMap, "power_id");
			//对part_id字符串拆分
			if(power_id.equals("")){
				String sql="delete from t_power_part where part_id=?";
				jdbcTemplate.update(sql,part_id);
				return 1;
			}
			String[] power_ids = power_id.split(",");
			int power;
				try {
					if(power_ids.length>0){
						String sql="delete from t_power_part where part_id=?";
						jdbcTemplate.update(sql,part_id);
						for(int i=0;i<power_ids.length;i++){
							
							power = Integer.parseInt(power_ids[i]);
							String sqlI="insert into t_power_part(power_id,part_id,create_time,update_time) values(?,?,now(),now())";
						    jdbcTemplate.update(sqlI,power,part_id);
						}
						
						return 1;
					}else{
						String sql="delete from t_power_part where part_id=?";
						jdbcTemplate.update(sql,part_id);
						return 1;
					}
				} catch (Exception e) {
					this.logger.info("角色权限更新失败！");
					e.printStackTrace();
					return 0;
				}
		}
}
